﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ZXthex.EditorUI
{
    public static class EUIHelper
    {

        static Stack<int> deepIndices = new Stack<int>(7);
        public static void TravlesalTransform<T>(
            T child, 
            Func<T, T> getParentFunc, 
            Func<T, int> childCountFunc, 
            Func<T, int, T> getChildFunc,
            Func<T, bool> ignoreFunc,
            Action<T> doAction
            )
        {
            if (ignoreFunc(child))
                return;

            doAction(child);

            if (childCountFunc(child) == 0)
                return;

            var parent = child;
            child = getChildFunc(child,0);
            deepIndices.Push(0);
            while (true)
            {
                var active = !ignoreFunc(child);
                if (active)
                    doAction(child);

                if (childCountFunc(child) > 0 && active)
                {
                    parent = child;
                    deepIndices.Push(0);
                    child = getChildFunc(child, 0);
                }
                else
                {
                    int nextIndex;
                    do
                    {
                        nextIndex = -1;
                        if (deepIndices.Count==0)
                            break;
                        parent = getParentFunc(parent);
                        child = getParentFunc(child);
                        nextIndex = deepIndices.Pop() + 1;
                    }
                    while (nextIndex >= childCountFunc(child));

                    if (nextIndex == -1)
                        break;
                    parent = child;
                    child = getChildFunc(child, nextIndex);
                    deepIndices.Push(nextIndex);
                }
            }
        }
    }
}